<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <p>有限状态机</p>
  <button id="btn"></button>

  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  <script src="./03-javascript-state-machine.js"></script>
  <script>
    // 状态模式 状态机
    var fsm = new StateMachine({
      init: '收藏', //初始状态
      transitions: [{
          name: 'doStore',
          from: '收藏',
          to: '取消收藏'
        },
        {
          name: 'deleteStore',
          from: '取消收藏',
          to: '收藏'
        }
      ],
      methods: {
        onDoStore: function () {
          console.log('收藏成功')
          updateText()
        },
        onDeleteStore: function () {
          console.log('已取消收藏')
          updateText()
        }
      }
    })

    var $btn = $('#btn')

    // 点击事件
    $btn.click(function () {
      if (fsm.is('收藏')) {
        fsm.doStore()
      } else {
        fsm.deleteStore()
      }
    })

    // 更新文案
    function updateText() {
      $btn.text(fsm.state)
    }

    // 初始化文案
    updateText()
  </script>
</body>

</html>